package com.xjtu.platform.answer.answer.impl;

import com.xjtu.platform.answer.answer.*;
import com.xjtu.platform.answer.answer.dao.AnswerDao;
import com.xjtu.platform.common.Cache;
import com.xjtu.platform.common.CommonService;
import com.xjtu.platform.common.Constants;
import com.xjtu.platform.common.CurrentUser;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Service
@Transactional
public class AnswerServiceImpl implements AnswerService {
    private static String prefix = "ANSWER";
    private static int LIMIT_TIME = 15;
    @Resource
    private AnswerDao answerDao ;

    @Resource
    private CommonService commonService;

    private String findNewQues(CurrentUser user)
    {
        System.out.println(user.getFavor());
        String question_id = answerDao.findQues(user);
        if(question_id==""||question_id==null)
        {
            question_id = answerDao.findDoableQuestion(user);
        }
        System.out.println("new question id");
        System.out.println(question_id);
        return question_id;
    }

    @Override
    public QuestionDto getQuestInfo(CurrentUser user) {
        String role_id = answerDao.getRoleID(user.getUserId());
        if(role_id.equals("checker"))
        {
            user.setRank(1);
        }

        else if(role_id.equals("respondent"))
        {
            user.setRank(0);
        }
        System.out.println("rankk!!!!!!!!!!!");
        System.out.println(user.getRank());
        String question_id;
        Long limitTime = new Long(0);
        Long currentTime = System.currentTimeMillis();
        Long time = new Long(-2000000);

        Cache cacheContent = commonService.findCacheByKey(prefix+user.getUserId());
        AnswerDto answerDto = new AnswerDto();
        if(cacheContent!=null&&cacheContent.getValue()!=null){
            System.out.println("find in cache!!!");
            answerDto.setQuestion_id(cacheContent.getValue());
            answerDto.setUser_id(user.getUserId());
            time = cacheContent.getTime();
        }
        if(cacheContent!=null &&cacheContent.getValue()!=null &&
                answerDao.findAnswer(answerDto)==null && currentTime-time<1000*LIMIT_TIME)
        {
            question_id =  cacheContent.getValue();
            limitTime = 1000*LIMIT_TIME-(currentTime-time);
        }
        else{
            question_id = findNewQues(user);
            limitTime = new Long(LIMIT_TIME*1000);
            answerDao.decreaseCount(question_id);
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                public void run() {
                    answerDto.setUser_id(user.getUserId());
                    answerDto.setQuestion_id(question_id);
                    if(answerDao.findAnswer(answerDto)==null)
                    {
                        answerDao.increaseCount(question_id);
                    }
                }
            }, LIMIT_TIME*1000);// 设定指定的时间time,此处为2000毫秒
            System.out.println("user is @@");
            System.out.println(user.getUserId());
            commonService.setCache(prefix+user.getUserId(),question_id);
        }

        if(question_id==null||question_id=="")
        {
            System.out.println("empty!!!!!!!");
            return null;
        }

        String request_id = answerDao.getRequestByQuest(question_id);
        requestDto requestInfo =answerDao.getQuestContentAndModeByRequestId(request_id);
        ArrayList<OptionDto> options = answerDao.getOptions(request_id);
        QuestionDto questionDto = new QuestionDto();
        String path = answerDao.getPathByQuest(question_id);

        questionDto.setQuestion_id(question_id);
        questionDto.setPath(path);
        questionDto.setRequest_id(request_id);
        questionDto.setOptions(options);
        questionDto.setQuestion_content(requestInfo.getQuestion_content());
        questionDto.setMode(requestInfo.getMode());
        questionDto.setLimitTime(limitTime);
        return questionDto;
    }

    @Override
    public void createAnswer(AnswerDto ans) {
        if(checkCache(ans)){
            String record_id = UUID.randomUUID().toString();
            ans.setRecord_id(record_id);
            commonService.deleteCache(prefix+ans.getUser_id());
            answerDao.insertAnswer(ans);//插入答案
            reward(ans);//奖励
            QuestionDto ques = new QuestionDto();
            ques.setQuestion_id(ans.getQuestion_id());
            if(answerDao.checkCount(ans.getQuestion_id()).equals(0))//最后一个该问题的答案则修改问题状态
            {
                Integer ansCount = answerDao.checkAnsSame(ans.getQuestion_id());
                if(ansCount.equals(1))
                {
                    answerDao.confirm(ans);
                    checkStatusByQuestion(ans);//最后一个该需求的答案则修改需求状态
                    ques.setRank(Constants.QUESTION_EXPORTABLE);
                }
                else {
                    answerDao.increaseCount(ans.getQuestion_id());
                    ques.setRank(Constants.QUESTION_CHECKABLE);
                }
                answerDao.setQuesRank(ques);
            }
        }
    }

    @Override
    public List<AnswerDto> getReferenceList(String question_id) {
        return answerDao.getReferenceList(question_id);
    }

    @Override
    public boolean confirm(AnswerDto ans) {
        System.out.println("confirming!!!!!");
        if(checkCache(ans)){
            commonService.deleteCache(prefix+ans.getUser_id());
            QuestionDto ques = new QuestionDto();
            ques.setQuestion_id(ans.getQuestion_id());
            ques.setRank(Constants.QUESTION_EXPORTABLE);
            answerDao.setQuesRank(ques);
            answerDao.confirm(ans);
            checkStatusByQuestion(ans);
            String record_id = UUID.randomUUID().toString();
            ans.setRecord_id(record_id);
            answerDao.insertAnswer(ans);
            return true;
        }
        return false;
    }

    @Override
    public boolean reject(AnswerDto answer) {
        System.out.println("rejecting!!!");
        if(checkCache(answer)) {
            QuestionDto ques = new QuestionDto();
            ques.setQuestion_id(answer.getQuestion_id());
            ques.setRank(Constants.QUESTION_EXPORTABLE);
            answerDao.reject(answer);
            checkStatusByQuestion(answer);
            answerDao.setQuesRank(ques);
            commonService.deleteCache(prefix+answer.getUser_id());
            return true;
        }
        return false;
    }

    public boolean checkCache(AnswerDto ans) {
        System.out.println("????");
        System.out.println(ans.getQuestion_id());
        Cache cache = commonService.findCacheByKey(prefix+ans.getUser_id());
        if(cache==null||cache.getValue()==null||cache.getTime()==null)
        {
            System.out.println("check! no such cache");
            return false;
        }
        Long currentTime = System.currentTimeMillis();
        Long dTime = currentTime - cache.getTime();
        boolean check = ((cache.getValue().equals(ans.getQuestion_id()))&&(dTime<LIMIT_TIME*1000));
        System.out.println("check!");
        System.out.println(check);
        System.out.println(ans.getQuestion_id());
        System.out.println(cache.getValue());
        System.out.println(currentTime);
        System.out.println(cache.getTime());
        System.out.println(dTime);
        System.out.println(dTime<LIMIT_TIME*1000);
        System.out.println((cache.getValue().equals(ans.getQuestion_id())));
        if((cache.getValue().equals(ans.getQuestion_id()))&&(dTime<LIMIT_TIME*1000) )
        {
            return true;
        }
        return false;
    }

    public boolean checkStatus(String request_id) {
        Integer doAble = answerDao.findDoable(request_id);
        if(doAble==0)
        {
            Integer checkAble = answerDao.findCheckAble(request_id);
            if(checkAble==0)
            {
                requestDto request = new requestDto();
                request.setStage(Constants.REQUEST_EXPORTABLE);
                request.setRequest_id(request_id);
                answerDao.setRequestStage(request);
                return true;
            }
            requestDto request = new requestDto();
            request.setStage(Constants.REQUEST_CHECKABLE);
            request.setRequest_id(request_id);
            answerDao.setRequestStage(request);
            return true;
        }
        return false;
    }

    public boolean reward(AnswerDto answer) {
        Integer credit = answerDao.checkCredit(answer);
        answer.setCredit(credit+Constants.CREDIT_PER_QUES);
        return answerDao.setCredit(answer);
    }

    public boolean checkStatusByQuestion(AnswerDto answer) {
        String request_id = answerDao.getRequestByQuest(answer.getQuestion_id());
        return checkStatus(request_id);
    }

}
